package cn.psvmc.cxzapi.service.customer;

import cn.psvmc.cxzapi.config.ConfigKey;
import cn.psvmc.cxzapi.config.mybatisplus.service.impl.AbstractService;
import cn.psvmc.cxzapi.exception.ServiceException;
import cn.psvmc.cxzapi.mapper.customer.TCustomerAuthMapper;
import cn.psvmc.cxzapi.mapper.customer.TCustomerMapper;
import cn.psvmc.cxzapi.model.common.SearchEntity;
import cn.psvmc.cxzapi.model.customer.TCustomer;
import cn.psvmc.cxzapi.response.Result;
import cn.psvmc.cxzapi.response.ResultGenerator;
import cn.psvmc.cxzapi.service.system.ServiceUtil;
import cn.psvmc.cxzapi.util.ToolUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 客户表 服务实现类
 *
 * @Author auto
 * @Date 2024-08-12
 */
@Service
@Slf4j
public class TCustomerService extends AbstractService<TCustomerMapper, TCustomer> {

    @Resource
    private TCustomerMapper tCustomerMapper;
    @Resource
    private TCustomerAuthMapper customerAuthMapper;
    @Resource
    private ServiceUtil serviceUtil;

    /**
     * @Date auto 2024-08-12 新增客户表
     * @Param tCustom 客户表
     * @Return int
     */
    public Result add(TCustomer tCustomer) {
        Map<String, Object> map = tCustomerMapper.findByPhone(tCustomer.getPhone());
        String name = tCustomer.getName();
        if (map == null) {
            tCustomerMapper.insert(tCustomer);
            map = new HashMap<>();
            map.put("name", name);
            map.put("customerid", tCustomer.getCustomerid());
            map.put("phone", tCustomer.getPhone());
            map.put("userid", tCustomer.getUserid());
            map.put("rversion", 1);
        } else {
            throw new ServiceException("该手机号已被注册！");
        }
        return ResultGenerator.genSuccessResult("保存成功！", map);
    }

    /**
     * @Date auto 2024-08-12 更新客户表
     * @Param tCustom 客户表模型
     * @Return int
     */
    public int edit(TCustomer tCustomer) {
        TCustomer originTCustomer = checkObj(tCustomer.getCustomerid());//校验顾客是否存在

        // 比较数据版本号
        if (!originTCustomer.getRversion().equals(tCustomer.getRversion())) {
            throw new ServiceException("数据已更新，请刷新后重试！");
        }

        // 字段为null 不更新
        return tCustomerMapper.updateById(tCustomer);
    }

    //校验顾客是否存在
    private TCustomer checkObj(Integer customerid) {
        // 通过id查询数据处理 详情
        TCustomer originTCustomer = tCustomerMapper.selectById(customerid);
        if (originTCustomer == null) {
            throw new ServiceException("未查询到对应的客户表信息！");
        }
        return originTCustomer;
    }

    /**
     * @Date auto 2024-08-12 查询客户表详情
     * @Param id 唯一id
     * @Return cn.psvmc.cxzapi.model.custom.TCustom
     */
    public TCustomer detail(Integer id) {
        return tCustomerMapper.selectById(id);
    }

    /**
     * @Date auto 2024-08-12 查询客户表列表
     * @Param iPage 分页
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<cn.psvmc.cxzapi.model.custom.TCustom>
     */
    public IPage<Map> list(Page<TCustomer> iPage, SearchEntity entity) {
        IPage<Map> page = tCustomerMapper.listAll(iPage, entity);
        for (Map record : page.getRecords()) {
            int isMember = 0;
            if (ToolUtils.isNotEmpty(record.get("bizCardNo"))) {
                isMember = 1;
            }
            record.put("isMember", isMember);
        }
        return page;
    }

    /**
     * @Description 获取临时访问凭证
     * @Date 2024/8/12 20:49
     * @Author YWX
     * @Param []
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    public Result getSts() {
        return ResultGenerator.genSuccessResult("查询成功！", serviceUtil.getSts());
    }

    /**
     * @Description 使用临时访问凭证上传文件至OSS
     * @Date 2024/8/12 21:31
     * @Author YWX
     * @Param [file, map]
     * @Return cn.psvmc.cxzapi.response.Result
     **/
    public Result uploadOss(MultipartFile file, Map<String, String> map) {
        // OSS访问域名。以华东1（杭州）地域为例，填写为https://oss-cn-hangzhou.aliyuncs.com。其它Region请按实际情况填写。
        String endpoint = "https://" + ConfigKey.ossEndpoint;
        // 从环境变量中获取步骤5生成的临时访问密钥AccessKey ID和AccessKey Secret，非阿里云账号AccessKey ID和AccessKey Secret。
        String accessKeyId = map.get("accessKeyId");
        String accessKeySecret = map.get("accessKeySecret");
        // 从环境变量中获取步骤5生成的安全令牌SecurityToken。
        String securityToken = map.get("securityToken");

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, securityToken);
        try {
            // 将本地文件exampletest.txt上传至examplebucket。
            PutObjectRequest putObjectRequest = new PutObjectRequest(ConfigKey.bucketName, "exampletest.txt", file.getInputStream());

            ObjectMetadata metadata = new ObjectMetadata();
            // 上传文件时设置存储类型。
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // 上传文件时设置读写权限ACL。
            metadata.setObjectAcl(CannedAccessControlList.Private);
            putObjectRequest.setMetadata(metadata);
            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } catch (Exception e) {
            log.error("上传文件至OSS出错: {}", e.getMessage());
            return ResultGenerator.genFailResult("上传文件至OSS出错: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ResultGenerator.genSuccessResult("上传文件至OSS成功！");
    }

    /**
     * @Description 选择列表
     * @Date 2024/8/19 8:57
     * @Author YWX
     * @Param [queryPage, entity]
     * @Return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map>
     **/
    public IPage<Map> listForSel(Page<TCustomer> queryPage, SearchEntity entity) {
        return tCustomerMapper.listForSel(queryPage, entity);
    }

    /**
     * @Description 获取认证资料
     * @Date 2024/8/24 10:40
     * @Author YWX
     * @Param [customerid]
     * @Return java.util.Map<java.lang.String, java.lang.Object>
     **/
    public Map<String, Object> getAuth(Integer customerid) {
        return customerAuthMapper.findByCustomerId(customerid);
    }


}
